package com.winz.cultureapp.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;

import com.mine.xrecyclerview.XRecyclerView;
import com.mine.xrecyclerview.rcvadapter.OnItemClickListener;
import com.winz.cultureapp.R;
import com.winz.cultureapp.activity.PublicationMp3Activity;
import com.winz.cultureapp.activity.PublicationVideoActivity;
import com.winz.cultureapp.adapter.xrcv.PublicationAdapter;
import com.winz.cultureapp.base.BaseFragment;
import com.winz.cultureapp.constants.Constants;
import com.winz.cultureapp.entity.EventBusBean;
import com.winz.cultureapp.entity.PublicationListBean;
import com.winz.cultureapp.http.DownloadUtils;
import com.winz.cultureapp.http.OnResponeListener;
import com.winz.cultureapp.http.request.RequestFactory;
import com.winz.cultureapp.http.util.HttpUitls;
import com.winz.cultureapp.utils.JsonUtil;
import com.winz.cultureapp.utils.Logger;
import com.winz.cultureapp.utils.MarginDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;

/**
 * 研究成果及多媒体出版物
 */
public class PublicationFragment extends BaseFragment implements OnItemClickListener, XRecyclerView.LoadingListener {
    @BindView(R.id.xrcv_publication)
    public XRecyclerView mXrcv_publication;

    private boolean isRefresh = true;
    private int limit = 12;
    private int page = 1;
    private int totalPage = 0;

    private List<PublicationListBean.DataBean.ListBean> mDatas;
    private PublicationAdapter mAdapter;

    private String type = ""; // 筛选类型

    private Uri mPdfUriFromFile;
    private File pdfFile;

    private static final String FILE_PROVIDER_AUTHORITY = "com.winz.cultureapp.fileprovider";
    private String researchCategoryId = "0";

    public static PublicationFragment getInstance() {

        PublicationFragment fragment = new PublicationFragment();

        return fragment;
    }

    @Override
    protected int contentView() {
        return R.layout.fragment_publication;
    }

    @Override
    protected void initViews(View view) {
        mDatas = new ArrayList<>();
        // XrecyclerView
        GridLayoutManager manager = new GridLayoutManager(mContext, 3);
        mXrcv_publication.addItemDecoration(new MarginDecoration(mXrcv_publication, getResources().getDimensionPixelOffset(R.dimen.layout_padding_small), 3));
        mXrcv_publication.setLayoutManager(manager);
        mXrcv_publication.setPullRefreshEnabled(true);
        mXrcv_publication.setLoadingMoreEnabled(true);

        mAdapter = new PublicationAdapter(mContext, mDatas, R.layout.empty_view, R.layout.item_publication);

    }

    @Override
    protected void initEvents() {

        mXrcv_publication.setAdapter(mAdapter);
        mXrcv_publication.setLoadingListener(this);
        mAdapter.setOnItemClickListener(this);

    }

    @Override
    protected void loadDatas() {
        getList();
    }

    /**
     * 获取数据列表
     */


    private void getList() {
        showProgressDialog();

        HttpUitls.onGet("legacy_research", RequestFactory.getInstance().legacy(page+"",limit+"",researchCategoryId), new OnResponeListener<PublicationListBean>() {
            @Override
            public void onSuccess(PublicationListBean bean) {
                Logger.d("legacy==>>", JsonUtil.getJsonFromObj(bean));
                if (bean.code == 0) {
                    totalPage = bean.totalPage;
                    if (bean.data.list != null && bean.data.list.size() > 0) {
                        mXrcv_publication.setLoadingMoreEnabled(true);
                        if (isRefresh) {
                            mDatas.clear();
                            mDatas = bean.data.list;
                        } else {
                            mDatas.addAll(bean.data.list);
                        }
                    } else {
                        mDatas.clear();
                        PublicationListBean.DataBean.ListBean empty = new PublicationListBean.DataBean.ListBean();
                        empty.layout_type = -1;
                        mDatas.add(empty);
                        mXrcv_publication.setLoadingMoreEnabled(false);
                    }
                    mAdapter.setDatas(mDatas);
                } else {
                    showMsg(bean.msg);
                }
                if (isRefresh) {
                    mXrcv_publication.refreshComplete();
                } else {
                    mXrcv_publication.loadMoreComplete();
                }
                dismissProgressDialog();
            }

            @Override
            public void onFailed(String error) {
                dismissProgressDialog();
                showMsg(error);
                if (isRefresh) {
                    mXrcv_publication.refreshComplete();
                } else {
                    mXrcv_publication.loadMoreComplete();
                }
            }
        });
    }


    @Override
    public void onItemClick(ViewGroup parent, View view, int position) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(Constants.KEY.PUBLICATION.DATA, mDatas.get(position));
        switch (mDatas.get(position).researchCategory.researchCategoryId) {
            case "1000": // 视频
                startActivity(PublicationVideoActivity.class, false, bundle);
                break;
            case "1001": // 音频
                startActivity(PublicationMp3Activity.class, false, bundle);
                break;
            case "1002": // 图文
                // 下载pdf文件
                downloadPdf(mDatas.get(position));
                break;
        }

    }


    @Override
    public boolean onItemLongClick(ViewGroup parent, View view, int position) {
        return false;
    }

    /**
     * 下载PDF文件
     */
    private void downloadPdf(PublicationListBean.DataBean.ListBean bean) {
        pdfFile = createPdfFile();//创建用来保存照片的文件
        mPdfUriFromFile = Uri.fromFile(pdfFile);
        showProgressDialog("文件下载中,请稍候....");
        DownloadUtils.getInstance().download(bean.contentUrl, pdfFile, new DownloadUtils.OnFinishedListener() {
            @Override
            public void onFinished(String filePath) {
                dismissProgressDialog();
                galleryAddFile(mPdfUriFromFile);
                Intent intent = new Intent("android.intent.action.VIEW");
                intent.addCategory("android.intent.category.DEFAULT");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                Uri uri = null;
                File file = new File(filePath);
                if (file.exists()) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        //data是file类型,忘了复制过来
                        uri = FileProvider.getUriForFile(mContext, FILE_PROVIDER_AUTHORITY, new File(filePath));

                    } else {
                        uri = Uri.fromFile(new File(filePath));
                    }
                }
                //pdf文件要被读取所以加入读取权限
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(uri, "application/pdf");
//              startActivity(intent);
                startActivity(Intent.createChooser(intent, bean.title));
            }

            @Override
            public void onFailed(String error) {
                dismissProgressDialog();
                showMsg("下载失败");
            }
        });

    }

    /**
     * 创建用来存储pdf的文件，以时间来命名就不会产生命名冲突
     *
     * @return 创建的文件
     */
    private File createPdfFile() {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "pdf_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        File imageFile = null;
        try {
            imageFile = File.createTempFile(imageFileName, ".pdf", storageDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageFile;
    }

    /**
     * 刷新
     */
    @Override
    public void onRefresh() {
        isRefresh = true;
        page = 1;
        loadDatas();
    }

    /**
     * 加载
     */
    @Override
    public void onLoadMore() {
        isRefresh = false;
        if (page >= totalPage) {
            mXrcv_publication.setNoMore(true, true, "没有更多数据了");
        } else {
            page++;
            loadDatas();
        }
    }


    @Override
    protected void onVisible() {
        super.onVisible();

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onInvisible() {
        super.onInvisible();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void messageEventBus(EventBusBean<String> event) {
        if (event.type == 1) {
            researchCategoryId = event.t;
            if (!TextUtils.isEmpty(researchCategoryId)){
                getList();
            }
        }

    }

    /**
     * 将下载到的文件添加系统文体列表
     *
     * @param uri
     */
    private void galleryAddFile(Uri uri) {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);//ACTION_MEDIA_SCANNER_SCAN_FILE
        mediaScanIntent.setData(uri);
        mContext.sendBroadcast(mediaScanIntent);
    }
}
